<?php

namespace App\Models;

use Illuminate\Support\Facades\Cache;

//use Yadakhov\InsertOnDuplicateKey;

/**
 * 法务用户表
 */
class AiLawUsers extends Model
{

    protected $connection = 'mysql';
    protected $table = 'ai_law_users';
    protected $guarded = ['id'];

//    use InsertOnDuplicateKey;

    public static function boot()
    {
        parent::boot();

        //当保存完成时触发
        self::saved(function ($model) {
            // 清空查询用户信息缓存
            $key = config('cache_keys.ai_law_user') . $model->id;
            Cache::forget($key);
        });

        //当删除时触发
        self::deleted(function ($model) {
            // 清空查询用户信息缓存
            $key = config('cache_keys.ai_law_user') . $model->id;
            Cache::forget($key);
        });
    }

    /**
     * 查询用户信息
     *
     * @param $id
     * @param $refresh
     * @return mixed
     * @author  
     * @time 2024-01-23 14:49:21
     */
    public static function getAILawUser($id, $refresh = false)
    {
        $key = config('cache_keys.ai_law_user') . $id;
        $refresh && Cache::forget($key);

        return Cache::remember($key, 300, function () use ($id) {
            // 保证 token,password 字段安全
            $fields = ['id', 'user_name', 'phone', 'profile_photo', 'gender',
                'birthday', 'province', 'city', 'area', 'info', 'wx_open_id',
                'ai_token', 'created_at', 'updated_at', 'last_login_at'];
            return AiLawUsers::query()->with('vipUser')->find($id, $fields);
        });
    }

    /**
     * 关联vip信息
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     * @author  
     * @time 2024-01-23 14:48:48
     */
    public function vipUser()
    {
        return $this->belongsTo('App\Models\AiLawVipUsers', 'id', 'user_id')
            ->select("user_id", "user_level", "vip_expire_at", "robot_question_times", "created_at");
    }

    public function paidService()
    {
        return $this->belongsTo('App\Models\AiLawPaidService', 'user_level', 'service_code')
            ->select("id", "service_code", "service_type", "service_name", "expired_days", "created_at");
    }


}
